package com.company;

/**
 * https://stackoverflow.com/questions/4906799/why-invoke-thread-currentthread-interrupt-in-a-catch-interruptexception-block
 *
 * @date : 2023-06-08 下午6:40
 */

public class P056_ThreadInterrupt {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new InterruptedSleepingRunner());
        thread.start();
        // Giving 10 seconds to finish the job.
        Thread.sleep(10000);
        // Let me interrupt
        thread.interrupt();
    }

    public static class InterruptedSleepingRunner implements Runnable {
        @Override
        public void run() {
            doAPseudoHeavyWeightJob();
        }

        private void doAPseudoHeavyWeightJob() {
            for (int i = 0; i < Integer.MAX_VALUE; i++) {
                // You are kidding me
                System.out.println(i);
                // Let me sleep <evil grin>
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println("Thread interrupted Exiting...");
                    break;
                } else {
                    sleepBabySleep();
                }
            }
        }

        protected void sleepBabySleep() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("异常1");
                Thread.currentThread().interrupt();
                System.out.println("异常2");
            }
        }
    }
}
